<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
          <!--          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>-->

        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList" :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  border row-key="id"
                  style="width:100%;margin-bottom: 20px;"
        >
          <!--          <el-table-column type="selection"></el-table-column>-->
          <el-table-column label="ID" prop="id"></el-table-column>
          <el-table-column label="活动名称" prop="name"></el-table-column>
          <el-table-column label="活动标题" prop="title"></el-table-column>
          <el-table-column label="活动内容" prop="content"></el-table-column>
          <el-table-column label="活动展示图" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.picture" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.picture" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="详情图" prop="detail_picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.detail_picture" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.detail_picture" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="展示URL" prop="h5_url"></el-table-column>
          <el-table-column label="添加时间" prop="created_at"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.add_time === 0" icon="el-icon-edit" plain size="mini" type="primary"
                         @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              <el-button plain size="mini" type="primary" @click="handleSend(scope.row)">发送
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--        分页-->
        <cus-pagination
          :limit.sync="editRulesForm.perPage"
          :page.sync="editRulesForm.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose('editRulesForm')"
    >
      <el-form ref="editRulesForm" :model="editRulesForm" :rules="editRulesFormRules" class="demo-ruleForm"
               label-width="120px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="editRulesForm.name" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="editRulesForm.title" placeholder="请输入活动标题"></el-input>
        </el-form-item>
        <el-form-item label="活动内容" prop="content">
          <el-input v-model="editRulesForm.content" placeholder="请输入活动内容"></el-input>
        </el-form-item>
        <el-form-item label="小图标" prop="picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="specialFlagBigList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传小图标</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动类型" prop="show_type">
          <el-select
            v-model="editRulesForm.show_type"
            clearable
            filterable
            placeholder="请选择活动类型"
          >
            <el-option
              v-for="item in option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editRulesForm.show_type === 2" key="detail_picture" label="详情图" prop="detail_picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="specialFlagBigList2"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove2"
            :on-success="handleSpecialFlagBigSuccess2"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传大图标</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="editRulesForm.show_type === 3" key="h5_url" label="外部链接" prop="h5_url">
          <el-input v-model="editRulesForm.h5_url" placeholder="请输入外部链接"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <el-dialog v-dialogDrag :visible.sync="sendVisible" title="发送">
      <el-form
        ref="sendForm"
        :model="sendForm"
        :rules="sendFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="发送内容">
          <div v-if="sendMessageType === 2">
            <img
              v-for="(item, index) in sendContent"
              :key="index"
              :src="item"
              style="width:80px;height:80px;margin:5px;"
            />
          </div>
          <div v-if="sendMessageType === 1" v-html="sendContent"></div>
        </el-form-item>
        <el-form-item label="发送用户" prop="user_type">
          <el-select v-model="sendForm.user_type" placeholder="请选择用户类型">
            <el-option
              v-for="item in chooseUser"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="sendForm.user_type === 2"
          label="用户编号(多个用逗号隔开)"
          prop="user_codes"
        >
          <el-input
            v-model="sendForm.user_codes"
            placeholder="请输入用户ID"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="sendVisible = false">返回</el-button>
          <el-button type="primary" @click="sendSubmit">发送</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addMessage, editMessage, listData, sendMessage } from '@/api/activityMessage'

export default {
  data() {
    return {
      sendContent: undefined,
      sendMessageType: 1,
      chooseUser: [
        { value: 1, label: '全部' },
        { value: 2, label: '指定' },
        { value: 3, label: '男性' },
        { value: 4, label: '女性' }
      ],
      sendVisible: false,
      sendFormRules: {
        user_type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
      },
      sendForm: {
        user_type: undefined,
        user_codes: undefined
      },
      option: [
        { value: 1, label: '普通' },
        { value: 2, label: '详情页' },
        { value: 3, label: 'H5页面' }
      ],
      confirmBtn: false,
      specialFlagBigList: [],
      specialFlagBigList2: [],

      // 要修改的当前行的id
      row_id: 0,
      provinceList: [],
      cityList: [],
      // 表单规则
      editRulesFormRules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入活动内容', trigger: 'blur' }],
        picture: [{ required: true, message: '请上传展示图片', trigger: 'blur' }],
        detail_picture: [{ required: true, message: '请上传详情图', trigger: 'blur' }],
        h5_url: [{ required: true, message: '请输入外部链接', trigger: 'blur' }],
        show_type: [{ required: true, message: '请进行活动类型', trigger: 'blur' }]

      },
      editRulesForm: {
        id: undefined,
        title: undefined,
        content: undefined,
        picture: undefined,
        detail_picture: undefined,
        h5_url: undefined,
        show_type: undefined,
        name: undefined,
        page: 1,
        perPage: 10
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    sendSubmit() {
      this.$refs.sendForm.validate(valid => {
        if (valid) {
          if (this.sendForm.user_type === 2) {
            if (
              this.sendForm.user_codes === undefined ||
              !this.sendForm.user_codes.trim()
            ) {
              this.$message.warning('请输入用户编号')
              return
            }
          } else {
            this.sendForm.user_codes = undefined // 置空
          }
          postSendData(this.row_id, this.sendForm).then(response => {
            if (response.code === 200) {
              this.getList()
              this.sendVisible = false
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
            }
          })
        }
      })
    },
    handleSend(row) {
      if (this.confirmBtn) return
      let data = {
        id: row.id
      }
      sendMessage(data).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    },
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('请上传JPG/PNG格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleSpecialFlagBigSuccess() {
      this.editRulesForm.picture = this.ossLastImgUrl
      this.specialFlagBigList = [{ url: this.ossLastImgUrl }]
    },
    handleSpecialFlagBigRemove() {
      this.specialFlagBigList = []
    },
    handleSpecialFlagBigSuccess2() {
      this.editRulesForm.detail_picture = this.ossLastImgUrl
      this.specialFlagBigList2 = [{ url: this.ossLastImgUrl }]
    },
    handleSpecialFlagBigRemove2() {
      this.specialFlagBigList2 = []
    },
    getList() {
      this.listLoading = true
      listData().then((response) => {
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    // 点击新增
    handleCreate() {
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      // row)
      this.row_id = row.id

      this.editRulesForm = {
        id: row.id,
        content: row.content,
        picture: row.picture,
        detail_picture: row.detail_picture,
        h5_url: row.h5_url,
        name: row.name,
        title: row.title,
        show_type: row.show_type
      },
        this.specialFlagBigList = [{ url: row.picture }]
      this.specialFlagBigList2 = [{ url: row.detail_picture }]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.editRulesForm = {
          title: undefined,
          content: undefined,
          picture: undefined,
          detail_picture: undefined,
          h5_url: undefined,
          show_type: undefined,
          name: undefined
        }
      })

      this.specialFlagBigList = []
      this.specialFlagBigList2 = []

    },
    submitForm(formName) {
      if (this.confirmBtn) return

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true
          if (this.dialogStatus === 'create') {
            addMessage(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          } else {
            editMessage(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          }
        } else {
          // 'error submit!!');
          return false
        }
      })
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-upload-list__item {
  transition: none !important;
}

/deep/ .el-upload-list--picture {
  max-height: 103px !important;
  overflow: hidden;
}
</style>
